#/*************************************************************************
#    > File Name: Lib/BASDA_Operation.py
#    > Author: Yan Wang
#    > Mail: wangyan@imnu.edu.cn
#    > Created Time: 2022年05月26日 星期四 15时22分43秒
# ************************************************************************/
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from File_Operation import *
from List_Operation import *
from Content_Operation import *
from Value_Calculation import *

# 利用BASDA的结果
def Replace_Para_in_BASDA(input_para, cut_cross):
	df_num=len(cut_cross)

	output_list={}
	for key in input_para:
		param_list_all=[]
		for cross_num in range(df_num):
			format_num=str(cross_num+1).rjust(2,"0")
			values={"fnum":format_num,"fvalue":cut_cross[cross_num]}
			input_dict=Trans_MultiValue_to_Dict(input_para[key],values)   #values传参到input_para[key]
			input_list=Trans_Dict_to_List(input_dict)   #将上述字典转化成列表
			param_list_all.append(input_list)   #在末尾添加input_list
		output_list[key]=param_list_all

	return(output_list)

# 利用BASDA的结果
def Replace_Para_in_BASDA_bk(input_path, input_file, input_xection, cut_cross):
	param_path_list_all=[]
	param_file_list_all=[]
	param_xection_list_all=[]
	df_num=len(cut_cross)

	for cross_num in range(df_num):
		path_dict=Trans_Value_to_Dict(input_path[0],cross_num+1)   #将cross_num+1传入input_path[0]中的{:value}位置上  
		param_path_list=Get_Replace_Sentence(path_dict, input_path[1])   #path_dict替换input_path[1]  
		param_path_list_all.append(param_path_list)
		
		
		file_dict=Trans_Value_to_Dict(input_file[0],cross_num+1)
		param_file_list=Get_Replace_Sentence(file_dict, input_file[1])
		param_file_list_all.append(param_file_list)
		
		input_xection_value_list=Get_Maplist_Key(input_xection[1])   #查找所有的key
		param_xection_list =input_xection[1]["file"].format(fnum=cross_num+1,fvalue=cut_cross[cross_num])
		param_xection_list_all.append([param_xection_list])
	return([param_path_list_all,param_file_list_all,param_xection_list_all])



# 将BASDA 最后的 output_table 中结果 significance 提取出来
# 生成 BASDA 的运行参数
def Generate_Multi_BASDA_Control_File(cut_cross,dir_name, input_para):
	target_folder=Copy_File(dir_name["source"],dir_name["target"])   #复制文件

# generate param files

	input_origin={}
	for key in input_para:
		input_origin[key] = input_para[key]["origin"]
	replaced_para=Replace_Para_in_BASDA(input_origin, cut_cross)   #
	for key in input_para:
		File_Replace_with_Para(replaced_para[key], input_para[key]["source"], target_folder, input_para[key]["labels"])

	return(replaced_para)



def Generate_multi_BASDA_Control_File_bk(cut_cross, event_kind):
	source = '/home/yancy/Software/BASDA/control/control_scan'
	target = '/home/yancy/Software/BASDA/control/control_scan_4b0j_{}'.format(event_kind)
	target_folder=Copy_File(source,target)

	origin_path_list={"process":"PROCESS                   : 10_bp3_4b0j_{}",
		          "out" :"OUTPUT_FOLDER             : \"events/Event_scan_{}\"",
				  "tmp" :"RECORD_FILE               : \"tmp/tmp_h_w4b_{}.dat\"",
				  "file":"INPUT_FILE                : \"file_{}.dat\""}

	origin_file_list={"file":"FILE_0            : xsection_{}.dat"}
#origin_xection_list={"file":"        /home/yancy/Software/ARCH_test/events/Event_Analyse_scan_4b0j_mh_mch_20/events/sigh_w4b_{fnum}.root        : {fvalue} "}
	origin_xection_list={"file":"        "+ARCH_tmp_folder+"events/sigh_w4b_{fnum}.root        : {fvalue} "}

  

	input_path_dict={"process":"{}",
	             "out" :"{}",
	             "tmp" :"{}",
			     "file":"{}"}
	input_file_dict={"file":"{}"}
	input_xection_dict={"file":"{}"}


#template
	path_source="path.dat"
	file_source="file.dat"
	xection_source="xsection.dat"


	path_labels={"PROCESS                   : 10_bp3_4b0j_1":0,"OUTPUT_FOLDER             : 'events/Event_scan_1'":0,"RECORD_FILE               : 'tmp/tmp_h_w4b_1.dat'":0, "INPUT_FILE                : 'file_1.dat'":0}
	file_labels={"FILE_0            : xsection_1.dat":0}
	xection_labels={"        file  : 1.554":0}


# generate param files
	input_path=[input_path_dict,origin_path_list]
	input_file=[input_file_dict,origin_file_list]
	input_xection=[input_xection_dict,origin_xection_list]

	[param_path_list_all,param_file_list_all,param_xection_list_all] = Replace_Para_in_BASDA(input_path, input_file, input_xection, cut_cross)
	File_Replace_with_Para(param_path_list_all, path_source, target_folder, path_labels)
	File_Replace_with_Para(param_file_list_all, file_source, target_folder, file_labels)
	File_Replace_with_Para(param_xection_list_all, xection_source, target_folder, xection_labels)


def Find_BASDA_OutputTable(BASDA_out_name,total_file_num):
    All_sig = []
    for file_num in range(total_file_num):
        format_num=str(file_num+1).rjust(2,"0")
        BASDA_file = BASDA_out_name.format(format_num)
        if not os.path.exists(BASDA_file):
            print("The folder {} does not exist".format(BASDA_file))
        label = {'\\hline': 1}
        word_list, input_line_list = Find_Line(BASDA_file, label)
        if len(input_line_list) == 0:
            All_sig.append('0')
        else:
            strings = word_list[(-2)]
            significance = strings.split()[(-1)]
            All_sig.append(significance[:-2])
    return(All_sig)
